#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <cstring>
#include <sys/wait.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char const *argv[])
{
    const char *filename = "./testFifo";
    int ret = access(filename, F_OK);
    if (ret != 0)
    {
        ret = mkfifo("./testFifo", 0644);
        if (ret == -1)
        {
            perror("mkfifo error:");
            _exit(-1);
        }
    }
    /* 创建进程*/
    pid_t pidFd = fork();
    if (pidFd < 0)
    {
        perror("fork error");
        _exit(-1);
    }
    else if (pidFd == 0)
    {
        /* 子进程 */
        int readFd = open(filename, O_RDONLY);
        if (readFd == -1)
        {
            perror("open read error");
            _exit(-1);
        }
        char buf[128] = {0};
        int readBytes = 0;
        while (1)
        {
            readBytes = read(readFd, buf, sizeof(buf));
            if (readBytes < 0)
            {
                perror("read error:");
                _exit(-1);
            }
            else if (readBytes > 0)
            {
                printf("child readBytes = %d,\t buf = %s\n", readBytes, buf);
                memset(buf, 0, sizeof(buf));
            }
            else
            {
                break;
            }
        }
        close(readFd);
    }
    else
    {
        /* 父进程 */
        int writeFd = open(filename, O_WRONLY);
        if (writeFd == -1)
        {
            perror("open fifo error");
            _exit(-1);
        }

        ifstream ifs;
        /*打开文件*/
        ifs.open("lyric.txt", ios::in | ios::out);
        if (ifs.is_open() == false)
        {
            perror("open lyric error");
            _exit(-1);
        }

        char buffer[128] = {0};

        while (ifs.eof() == false)
        {
            ifs.getline(buffer, sizeof(buffer));
            // cout << "buffer:" << buffer << endl;
            /*写道fifo管道里面*/
            write(writeFd, buffer, strlen(buffer));
            /*清空脏数据*/
            memset(buffer, 0, sizeof(buffer));

            usleep(100);
        }
        ifs.close();
    }

    return 0;
}
